package cn.org.timespace.ons.socket.mina.filter.command.concrete;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.session.IoSession;

import cn.org.timespace.ons.socket.mina.filter.ESCardProtocalPack;
import cn.org.timespace.ons.socket.mina.filter.command.AbstractESCardCommand;
import cn.org.timespace.ons.socket.mina.util.ProcessPackage;

/**
 * 信息终端第一次连接门户
 * @author wind
 *
 */
public class MachinesOnsTimesCommand extends AbstractESCardCommand {
	private final static Log log = LogFactory.getLog(MachinesOnsTimesCommand.class);
	private final static int numSta = 24;//信息机配置信息内容长度
	
	@Override
	public void processPackage(IoSession session, ESCardProtocalPack pack) {
		ESCardProtocalPack packReplay = ProcessPackage.getPackReplay(pack);
		if(checkPackage(pack, ESCardProtocalPack.SYNC_FRAME_NAME_UP)) {//消息正确
			//解析信息机配置信息
			String ms = analyticalMsg(pack);
			if(ms != null && !ms.equals("")){
				packReplay.setPackageContents(ms);
				packReplay.setCheckCodeAndPackageLength();
				log.debug("回复：" + packReplay.toString());

				session.write(packReplay.toString());
				try {
					Thread.sleep(3000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				session.close(false);
				return;
			}
			
		}
			//出错
			packReplay.setPackageContents("ERROR");
			packReplay.setCheckCodeAndPackageLength();
			log.debug(packReplay.toString());
			session.write(packReplay.toString());
			try {
				Thread.sleep(3000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			session.close(false);
		
	}
	
	/**
	 * 	数据交换状态信息
	 * @param pack
	 * @return
	 */
	public String analyticalMsg(ESCardProtocalPack pack) {
		String result = "";
		String packageContents = pack.getPackageContents();//包内容
		try{
			int contentLength = packageContents.length();
			if(contentLength != numSta) {//如果包内容长度不是numSta
				log.debug("包内容长度不是numSta,解析失败");
				return null;
			}
			
			//信息终端的三码组合ID
			String machinesGroupID = pack.getPackageContents();//信息终端的三码组合ID
			
		    // 1.取信息终端的组合ID
//			result = ProcessPackage.getMachinesFId(machinesGroupID);
			
			return result;
		}
		catch(Exception e) {
			log.error("解析失败");
			log.debug(e.toString());
		}
		return null;
	}
	
}
